<?php

namespace App\Services;

use Mtownsend\XmlToArray\XmlToArray;

class NodeService extends BaseService
{
    /**
     * wsdl地址
     */
    const WSDL_URL = 'http://9.1.3.95/bpm/WF_RunProcessPort?wsdl';

    /**
     * xml基础元数据
     */
    const XML = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://server.ws.linkey.cn/"><soapenv:Header/><soapenv:Body><ser:runProcess><docXml>';

    /**
     * 获取到操作人的username
     * @return string
     */
    public function getHandleUserName() : string
    {
        return auth('api')->user()->username ?? '';
    }

    /**
     * 生成参数数据
     * @param array $parameters
     * @return array
     * @throws \Exception
     */
    public function generateParameters(array $parameters) : array
    {
        $needParameters = [
            'docUnid',
            'nextNodeid',
            'remark',
        ];

        foreach ($needParameters as $value) {
            if (!isset($parameters[$value]) || empty($parameters[$value]) || !is_string($parameters[$value])) {
                throw new \Exception('节点操作，参数异常');
            }
        }

        return [
            'actionid'     => 'EndUserTask',
            'processid'    => '81df916c0da0a040950812d0de4b80dbd575',
            'docUnid'      => $parameters['docUnid'],
            'nextNodeid'   => $parameters['nextNodeid'],
            'nextUserList' => $parameters['nextUserList'] ?? '',
            'userid'       => $this->getHandleUserName() ?: ($parameters['userid'] ?? ''),
            'remark'       => $parameters['remark'],
            'sysid'        => 'pms',
            'syspwd'       => 'pms'
        ];
    }

    /**
     * 创建xml参数数据
     * @param array $requestData
     * @param array $parameters
     * @return string
     * @throws \Exception
     */
    public function generateXmlParametersData(array $requestData,array $parameters) : string
    {
        $xmlParametersXml = self::XML;

        $xmlParametersXml .= '</docXml>';

        $parameters = $this->generateParameters($parameters);

        array_walk_recursive($parameters,function ($value,$key) use (&$xmlParametersXml){
            $xmlParametersXml .= '<'.$key.'>'.$value.'</'.$key.'>';
        });

        $xmlParametersXml .= '</ser:runProcess></soapenv:Body></soapenv:Envelope>';

        return $xmlParametersXml;
    }

    /**
     * 将xml的数据转换成array
     * @param string $xml
     * @return array
     */
    public function xmlToArray(string $xml) : array
    {
        if (empty($xml)) {
            return [];
        }

        $array = XmlToArray::convert($xml);

        $array = $array['S:Body']['ns2:runProcessResponse'] ?? [];

        if (!empty($array) && is_array($array)) {
            $result = json_decode($array['return'] ?? '',true);

            if ($result['WF_SucessFlag'] == "1") {
                return [
                    'status'  => 'success',
                    'code'    => 200,
                    'message' => $result['WF_Msg']
                ];
            }

            return [
                'status'  => 'error',
                'code'    => 500,
                'message' => $result['WF_Msg']
            ];
        }

        return [
            'status'  => 'error',
            'code'    => 500,
            'message' => '审批失败，请重新审批'
        ];
    }

    /**
     * 发送节点请求信息
     * @param array $requestData
     * @param array $parameters
     * @return array
     * @throws \Exception
     */
    public function nodeHandle(array $requestData,array $parameters) : array
    {
        $soapService = new \SoapClient(self::WSDL_URL);

        $response = $soapService->__doRequest(
            $this->generateXmlParametersData($requestData,$parameters),
            self::WSDL_URL,
            'runProcess',
            1,
            0
        );

        return $this->xmlToArray($response);
    }


}
